import { type DirectiveBinding } from 'vue';

// 埋点事件类型
interface TrackEvent {
  id: string;
  action: string;
  logmap: Record<string, any>;
}

// 事件处理函数
const eventHandler = (el: HTMLElement, binding: DirectiveBinding, action: string) => {
  const id = binding.value.id;
  const logmap = (binding.value.logmap && binding.value.logmap()) || {};
  const event: TrackEvent = {
    id,
    action,
    logmap,
  };
  window.weblog.report(event);
}

const trackEventDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {

    // 当前埋点事件类型，不传默认为click事件
    const action = binding.arg || 'click';

    const clickEventHandler = () => {
      eventHandler(el, binding, action);
    }

    const dragEventHandler = () => {
      console.log('drag');
    }

    const inputEventHandler = (e: KeyboardEvent) => {
      if (e.key === 'Enter') {
        eventHandler(el, binding, 'click')
      }
    }

    // 保存事件处理函数用于销毁时移除事件
    (el as any)._clickEventHandler = clickEventHandler;
    (el as any)._dragEventHandler = dragEventHandler;
    (el as any)._inputEventHandler = inputEventHandler;

    // 点击埋点
    if (action === 'click') {
      el.addEventListener('click', clickEventHandler);
    }

    // 拖拽埋点
    if (action === 'drag') {
      el.addEventListener('dragstart', dragEventHandler);
    }

    // 问句框输入埋点（enter）
    if (action === 'input') {
      el.addEventListener('keydown', inputEventHandler);
    }
  },

  // 销毁时移除事件
  onUnmounted(el: HTMLElement) {
    // 如果绑定点击事件，则移除事件
    if ((el as any)._clickEventHandler) {
      el.removeEventListener('click', (el as any)._clickEventHandler);
    }
    // 如果绑定拖拽事件，则移除事件
    if ((el as any)._dragEventHandler) {
      el.removeEventListener('dragstart', (el as any)._dragEventHandler);
    }
    // 如果绑定输入事件，则移除事件
    if ((el as any)._inputEventHandler) {
      el.removeEventListener('keydown', (el as any)._inputEventHandler);
    }
  }
};

export default trackEventDirective;
